import React, { useState } from 'react';
import { View, Text, Textarea, Image } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Button, Input, Toast, Uploader } from '@nutui/nutui-react-taro';
import { IconFont } from '@nutui/icons-react-taro';
import { createPost, uploadImage, uploadVideo } from '../../services/post';
import './index.scss';

const Publish: React.FC = () => {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [images, setImages] = useState<string[]>([]);
  const [video, setVideo] = useState<string>('');
  const [uploading, setUploading] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [toastType, setToastType] = useState<'success' | 'warn'>('warn');

  // 上传图片
  const handleUploadImage = async () => {
    try {
      const res = await Taro.chooseImage({
        count: 9 - images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });
      
      setUploading(true);
      const tempFilePaths = res.tempFilePaths;
      
      // 使用模拟上传服务，返回网络图片
      const uploadPromises = tempFilePaths.map(path => uploadImage(path));
      const uploadedImages = await Promise.all(uploadPromises);
      
      setImages([...images, ...uploadedImages]);
      setToastType('success');
      setToastMessage('图片上传成功');
      setShowToast(true);
    } catch (error) {
      setToastType('warn');
      setToastMessage(error.errMsg || '图片上传失败');
      setShowToast(true);
    } finally {
      setUploading(false);
    }
  };

  // 上传视频
  const handleUploadVideo = async () => {
    try {
      const res = await Taro.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back'
      });
      
      setUploading(true);
      const tempFilePath = res.tempFilePath;
      // 使用模拟上传服务，返回网络视频
      const uploadedVideo = await uploadVideo(tempFilePath);
      
      setVideo(uploadedVideo);
      setToastType('success');
      setToastMessage('视频上传成功');
      setShowToast(true);
    } catch (error) {
      setToastType('warn');
      setToastMessage(error.errMsg || '视频上传失败');
      setShowToast(true);
    } finally {
      setUploading(false);
    }
  };

  // 移除图片
  const handleRemoveImage = (index: number) => {
    const newImages = [...images];
    newImages.splice(index, 1);
    setImages(newImages);
  };

  // 移除视频
  const handleRemoveVideo = () => {
    setVideo('');
  };

  // 发布文章
  const handlePublish = async () => {
    if (!title.trim()) {
      setToastType('warn');
      setToastMessage('请输入标题');
      setShowToast(true);
      return;
    }

    if (!content.trim()) {
      setToastType('warn');
      setToastMessage('请输入内容');
      setShowToast(true);
      return;
    }

    try {
      setPublishing(true);
      await createPost({
        title,
        content,
        images: images.length > 0 ? images : undefined,
        video: video || undefined
      });
      
      setToastType('success');
      setToastMessage('发布成功');
      setShowToast(true);
      
      // 清空表单
      setTitle('');
      setContent('');
      setImages([]);
      setVideo('');
      
      // 延迟跳转到首页
      setTimeout(() => {
        Taro.switchTab({ url: '/pages/index/index' });
      }, 1500);
    } catch (error) {
      setToastType('warn');
      setToastMessage(error.message || '发布失败');
      setShowToast(true);
    } finally {
      setPublishing(false);
    }
  };

  return (
    <View className="publish-container">
      <View className="publish-form">
        <View className="form-item">
          <Input 
            className="title-input"
            placeholder="请输入标题"
            value={title}
            onChange={(value) => setTitle(value)}
          />
        </View>
        
        <View className="form-item">
          <Textarea
            className="content-textarea"
            placeholder="请输入内容"
            value={content}
            onInput={(e) => setContent(e.detail.value)}
            maxlength={2000}
            autoHeight
          />
        </View>
        
        {/* 图片上传区域 */}
        <View className="form-item">
          <View className="upload-title">添加图片</View>
          <View className="upload-area">
            {images.map((img, index) => (
              <View key={index} className="upload-item">
                <Image src={img} className="upload-image" mode="aspectFill" />
                <View 
                  className="upload-remove" 
                  onClick={() => handleRemoveImage(index)}
                >
                  <IconFont name="close" />
                </View>
              </View>
            ))}
            
            {images.length < 9 && (
              <View 
                className="upload-add" 
                onClick={handleUploadImage}
              >
                <IconFont name="photograph" />
                <Text>添加图片</Text>
              </View>
            )}
          </View>
        </View>
        
        {/* 视频上传区域 */}
        {!video && images.length === 0 && (
          <View className="form-item">
            <View className="upload-title">添加视频</View>
            <View 
              className="upload-video-btn" 
              onClick={handleUploadVideo}
            >
              <IconFont name="video" />
              <Text>上传视频</Text>
            </View>
          </View>
        )}
        
        {video && (
          <View className="form-item">
            <View className="upload-title">
              视频
              <View 
                className="video-remove" 
                onClick={handleRemoveVideo}
              >
                <IconFont name="close" />
              </View>
            </View>
            <View className="video-preview">
              <Text className="video-name">视频已上传</Text>
            </View>
          </View>
        )}
      </View>
      
      <View className="publish-actions">
        <Button 
          type="primary" 
          block
          loading={publishing}
          disabled={uploading}
          className="publish-button"
          onClick={handlePublish}
        >
          发布
        </Button>
      </View>
      
      <Toast
        visible={showToast}
        content={toastMessage}
        onClose={() => setShowToast(false)}
        type={toastType}
        duration={2000}
      />
    </View>
  );
};

export default Publish; 